class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode dummy(-1);
        int carry = 0;
        ListNode* prev = &dummy;
        ListNode* pa = l1;
        ListNode* pb = l2;

        while (pa != nullptr || pb != nullptr) {
            int ai = pa == nullptr ? 0 : pa->val;
            int bi = pb == nullptr ? 0 : pb->val;
            int value = (ai + bi + carry) % 10;

            carry = (ai + bi + carry) / 10;
            prev->next = new ListNode(value);

            pa = pa == nullptr ? nullptr : pa->next;
            pb = pb == nullptr ? nullptr : pb->next;
            prev = prev->next;
        }
        if (carry > 0) {
            prev->next = new ListNode(carry);
        }
        return dummy.next;
    }
};
